package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.six.dto.ClaimRequestDTO;
import com.csxy.six.entity.ClaimLog;
import com.csxy.six.entity.FoundItem;
import com.csxy.six.mapper.ClaimLogMapper;
import com.csxy.six.service.ClaimService;
import com.csxy.six.service.FoundItemService;
import com.csxy.six.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class ClaimServiceImpl extends ServiceImpl<ClaimLogMapper, ClaimLog> implements ClaimService {

    @Autowired
    private FoundItemService foundItemService;

    @Override
    @Transactional
    public boolean requestClaim(ClaimRequestDTO claimRequestDTO, Long userId) {
        // 验证用户ID
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }

        // 验证拾物是否存在且未被认领
        FoundItem foundItem = foundItemService.getById(claimRequestDTO.getFoundItemId());
        if (foundItem == null) {
            throw new RuntimeException("未找到ID为" + claimRequestDTO.getFoundItemId() + "的拾物记录");
        }
        if (foundItem.getIsClaimed()) {
            throw new RuntimeException("该物品已被认领");
        }

        // 创建认领记录
        ClaimLog claimLog = new ClaimLog();
        claimLog.setFoundId(claimRequestDTO.getFoundItemId());
        claimLog.setClaimUserId(userId); // 确保设置了这个值
        claimLog.setStatus("待审核");
        claimLog.setContactInfo(claimRequestDTO.getContactInfo());
        claimLog.setClaimTime(LocalDateTime.now());

        return this.save(claimLog);
    }

    @Override
    @Transactional
    public boolean processClaim(Integer claimId, boolean approved, String remark, Long adminId) {
        // 验证管理员权限
        if (!SecurityUtil.isAdmin()) {
            throw new RuntimeException("无权限操作");
        }

        // 获取认领记录
        ClaimLog claimLog = getById(claimId);
        if (claimLog == null) {
            throw new RuntimeException("未找到ID为" + claimId + "的认领记录");
        }
        if (!"待审核".equals(claimLog.getStatus())) {
            throw new RuntimeException("该认领记录已处理");
        }

        // 更新认领状态
        claimLog.setStatus(approved ? "已通过" : "已拒绝");
        claimLog.setVerifyUserId(adminId);
        claimLog.setVerifyTime(LocalDateTime.now());
        claimLog.setVerifyRemark(remark);

        boolean result = updateById(claimLog);

        // 如果审核通过，更新拾物状态
        if (result && approved) {
            FoundItem foundItem = foundItemService.getById(claimLog.getFoundId());
            if (foundItem != null) {
                foundItem.setIsClaimed(true);
                foundItemService.updateById(foundItem);
            }
        }
        return result;
    }
}